using MediatR;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement;
using MediatR;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;

namespace RBAC.Write.Api.Application.Handler.ERP.SalesManagement
{
    public class AddCustomerCommandHandler : IRequestHandler<AddCustomerCommands, APIResult<int>>
    {
        private readonly IBaseRepository<Customer> customerRep;

        public AddCustomerCommandHandler(IBaseRepository<Customer> customerRep)
        {
            this.customerRep = customerRep;
        }

        public Task<APIResult<int>> Handle(AddCustomerCommands request, CancellationToken cancellationToken)
        {
            if (request == null || request.customer == null)
            {
                return Task.FromResult(new APIResult<int>
                {
                    Code = APIEnums.Fail,
                    Msg = "参数不能为空",
                    Data = 0
                });
            }

            try
            {
                // 基础字段：由 BaseEntity 提供，CreateTime/IsDeleted 默认已赋值
                var entity = request.customer;

                // 简单必填校验（可根据业务扩展）
                if (string.IsNullOrWhiteSpace(entity.CustomerName))
                {
                    return Task.FromResult(new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "客户名称不能为空",
                        Data = 0
                    });
                }

                // 使用 Dapper 的通用仓储新增，返回新插入记录的自增ID
                var newId = customerRep.Create(entity);

                return Task.FromResult(new APIResult<int>
                {
                    Code = APIEnums.Success,
                    Msg = "新增成功",
                    Data = newId
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<int>
                {
                    Code = APIEnums.Fail,
                    Msg = "新增失败：" + ex.Message,
                    Data = 0
                });
            }
        }
    }
}
